import React from 'react';
import './css/register.less';
import http from '../../utils/http';
import {startClock} from '../../utils/common';
import {VALIDCODE, VALIDPHONE,VALIDPWD} from '../../utils/valid';
import { Form } from 'react-validify';
import { Link } from 'react-router-dom';
// import { Toast } from '../components/Toast';

// 校验
const rules = {
  account: ['required', `regex:${VALIDPHONE.reg}`],
  msgCode: ['required', `regex:${VALIDCODE.reg}`],
  password: ['required', `regex:${VALIDPWD.reg}`]
}
const errorMessages = {
  'required.account': VALIDPHONE.required,
  'regex.account': VALIDPHONE.errMsg,
  'required.msgCode': VALIDCODE.required,
  'regex.msgCode': VALIDCODE.errMsg,
  'required.password': VALIDPWD.required,
  'regex.password': VALIDPWD.errMsg
}
const placeholders = {
  account: '请输入手机号',
  password: '请输入密码',
  msgCode: '请输入短信验证码'
}
let phoneCache = {}
let codeCache = {}
let phoneMsg = ''
let codeMsg = ''

class Register extends React.Component {
  state = {
    agree: true,
    type: 2,
    account: '',
    password: '',
    msgCode: '',
    timePsw:'发送验证码',
    isabledPwd:true,
    submitError: '',
    isCanclick:true,
    placeholders: {
      account: placeholders.account,
      password: placeholders.password,
      msgCode: placeholders.msgCode
    },
    isregister:false
  } 
  checkValid = (props) => {
    if(props.name==='account' || props.name==='msgCode') {
      this.setState({})
    }
  }
  // 校验组件
  Input = ({ error, onEnter, ...props }) => {
    if (props.name==='account' && props.value.length===11) {
      this.validphone(props)
    } else if (props.name==='msgCode' && props.value.length===4) {
      this.validCode(props)
    }
    return (
    <div>
      <input  autoComplete="off" {...props} style={{border: error 
        ||(props.name==='msgCode' && props.value.length===4 && !error && codeMsg)
        ||(props.name==='account' && props.value.length===11 && phoneMsg) ? '1px solid #C13431': ''}} onBlur={(e)=>{
        props.onBlur(e);
        this.checkValid(props);
        const holders = this.state.placeholders
        holders[props.name] = placeholders[props.name]
        this.setState({
          placeholders: holders
        })
      }}/>
      {error ? <div className="error-msg">{error}</div> : ''}
      {props.name==='account' && props.value.length===11 && !error && phoneMsg?<div className="error-msg">{phoneMsg}</div>:''}
      {props.name==='msgCode' && props.value.length===4 && !error && codeMsg?<div className="error-msg">{codeMsg}</div>:''}
    </div>
  )};
  //校验验证码
  validCode = (props) => {
    if (props.name==='msgCode' && props.value.length === 4 && !phoneMsg){
      if (!codeCache[props.value]) {
        http.get('/code/validate/msgCode',{
          params: {
            mobile: document.getElementById('reg-account').value,
            msgCode: props.value
          }
        })
        .then(data=> {
          if (data) {
            codeCache[props.value] = 1
            codeMsg = ''
          } else {
            codeCache[props.value] = 2
            codeMsg = '验证码输入错误'
          }
        }, err => {
        })
      } else if(codeCache[props.value]===1) {
        codeMsg = ''
      } else if(codeCache[props.value]===2) {
        codeMsg = '验证码输入错误'
      }
    }
  }
  //校验手机号
  validphone = (props) => {
    if (props.name==='account' && props.value.length === 11){
      if (!phoneCache[props.value]) {
        http.get('/register/isRegister',{
          params: {account: props.value}
        })
        .then(data=> {
          if (data) {
            phoneMsg = '该手机号已注册'
            phoneCache[props.value] = 1
          } else {
            phoneMsg = ''
            phoneCache[props.value] = 2
          } 
        }, err => {
          phoneCache[props.value] = 2
          if(err && err.code === 41003){
            phoneMsg = ''
          }
        })
      } else if(phoneCache[props.value]===1) {
        phoneMsg = '该手机号已注册'
      } else if(phoneCache[props.value]===2) {
        phoneMsg = ''
      }
    } 
  }
  getCode = event => {
    const data = {
      type: 1,
      account: document.getElementById('reg-account').value,
    }
    http.post('/code/send/msgCode', data)
    .then(data => {
      if(data){
        this.setState({
          isabledPwd:false
        })
      }
    }, err => {
      this.setState({
        isabledPwd:true
      })
    })
  }
  save = values => {
    if (phoneMsg) return
    if (codeMsg) return
    if (!this.state.agree) return
    //点击后按钮为不可点
    this.setState({
      isCanclick:false,
      isregister:true      
    })
    // 校验
    const data = {
      account: values.account,
      password: values.password,
      msgCode: values.msgCode
    }
    http.post('/register/register', data)
    .then(data => {
      // Toast('注册成功');
      this.setState({
        isCanclick:true,
        isregister:false    
      })
      if(data){
        this.props.history.push('/login/')
      }
    }, err => {
      this.setState({
        isCanclick:true,  
        isregister:false 
      })
    })
  }
  clearHolder = (name) => {
    const holder = this.state.placeholders
    holder[name] = ''
    this.setState({placeholders: holder})
  }
  clearError = () => {
    this.setState({
      submitError: '',
    })
  }
  componentDidMount () {
    phoneCache = {}
    codeCache = {}
    phoneMsg = ''
    codeMsg = ''
  }
  render() {
    return (
      <div className="row register">
        <Form 
          rules={rules}
          errorMessages={errorMessages}
          className="register-content register-margin">
          <div className="register-login"><Link to="/login/">登录</Link></div>
          <div className="register-title text-center">账号注册</div>
          <div className="form-group re-filed-item">
            <div className="re-form-text">手机号</div>
            <this.Input 
                type="text"
                id="reg-account"
                name="account"
                onFocus = {()=>{
                  this.clearHolder('account')
                }}
                placeholder={this.state.placeholders.account}
                className="input-form"/>
          </div>
          <div className="form-group re-filed-item">
            <div className="re-form-text">密码</div>
            <this.Input type={this.state.textType} 
              name="password" 
              placeholder={this.state.placeholders.password}
              onFocus={()=>{
                this.setState({
                  textType:'password'
                })
                this.clearHolder('password')
              }}
              className="input-form"/>
          </div>
          <div className="form-group row register-code">
            <div className="col-md-6 col-xs-12">
              <this.Input 
                type="text"
                name="msgCode"
                placeholder={this.state.placeholders.msgCode}
                onFocus={()=>{
                  this.clearError()
                  this.clearHolder('msgCode')
                }}
                className="input-form"/>
            </div>
            <div className="col-md-6 col-xs-12">
              <button type="button" className="register-codebtn col-md-12 col-xs-12"  disabled={!this.state.isabledPwd?'disabled':''} onClick={()=>{
                this.setState({})
                const account = document.getElementById('reg-account').value
                if(!phoneMsg && account){
                        this.setState({
                        isabledPwd:false
                      })
                    startClock(true,60,(data)=>{
                        this.setState({
                            timePsw:data
                        })
                        if(this.state.timePsw==='发送验证码'){
                            this.setState({
                                isabledPwd:true
                            })
                        }
                    })
                    this.getCode()
                  }}
                }>
                {this.state.timePsw}
                </button>
              </div>
          </div>
          <div className="form-group re-agree">
              <label className="checkbox-inline">
                <input
                  className="re-checkbox"
                  type="checkbox"
                  checked = {this.state.agree?'checked':''}
                  onChange={(e) => {
                  this.setState({
                    agree: !this.state.agree
                  })
                }}/>
                <Link className="re-protocal" to="/protocol/" target="_blank">同意《皮皮鱼少儿英语用户注册协议》</Link>
              </label>
          </div>
          <div
            submit
            onClick={values => this.save(values)}
            style={{
            overflow: 'hidden'
          }}>
          {/* lodings */}
          {this.state.isregister?<img className="lodings" src={require('../../images/teacher-img/loding.svg')} alt="Loading icon" />:""}
            <input
              type="button"
              autoComplete="off"
              className="re-login-btn"
              value={this.state.isregister?"":"注册"}
              disabled={this.state.isCanclick?'':'disabled'}/>
          </div>
        </Form>
      </div>
    );
  }
}
export default Register;